/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ABMPerfiles.java
 *
 * Created on 17/07/2011, 03:06:37
 */

package ventanas;

import java.sql.Connection;
import conexiones.AdministradorDeConexiones;
import dao.PerfilesDao;
import java.awt.Dialog;
import java.awt.Frame;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import modelo.Perfil;
import modelo.Usuario;

/**
 *
 * @author Cristian Perez
 */
public class ABMPerfiles extends javax.swing.JDialog {

    DefaultListModel modeloPerfiles = new DefaultListModel();
    private Usuario usuarioLogueado = null;
    

    /** Creates new form ABMPerfiles */
    public ABMPerfiles(Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        listaPerfiles.setModel(modeloPerfiles);
        modeloPerfiles = (DefaultListModel) listaPerfiles.getModel();
        cargarLista();
        actualizarFormulario();
    }
    
    public ABMPerfiles(Dialog parent, boolean modal) {
        super(parent, modal);
        initComponents();

        listaPerfiles.setModel(modeloPerfiles);
        modeloPerfiles = (DefaultListModel) listaPerfiles.getModel();
        cargarLista();
        actualizarFormulario();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listaPerfiles = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        lblNombrePerfil = new javax.swing.JLabel();
        txtperfil = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        btnEliminar = new javax.swing.JButton();
        btnAlta = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();
        btnAsignarFuncion = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Perfiles");

        listaPerfiles.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Lista de Perfiles", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 2, 12))); // NOI18N
        listaPerfiles.setFont(new java.awt.Font("Tahoma", 1, 12));
        listaPerfiles.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaPerfilesMouseClicked(evt);
            }
        });
        listaPerfiles.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                listaPerfilesKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(listaPerfiles);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        lblNombrePerfil.setFont(new java.awt.Font("Tahoma", 3, 12));
        lblNombrePerfil.setText("PERFIL: ");

        txtperfil.setDisabledTextColor(new java.awt.Color(255, 255, 255));
        txtperfil.setEnabled(false);
        txtperfil.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtperfilKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblNombrePerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtperfil, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombrePerfil)
                    .addComponent(txtperfil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        btnEliminar.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnEliminar.setText("Eliminar");
        btnEliminar.setEnabled(false);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnAlta.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnAlta.setText("Nuevo perfil");
        btnAlta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAltaActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnCancelar.setText("Cancelar");
        btnCancelar.setEnabled(false);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnAceptar.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnAceptar.setText("Aceptar");
        btnAceptar.setEnabled(false);
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnAsignarFuncion.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnAsignarFuncion.setText("Asignar Función");
        btnAsignarFuncion.setEnabled(false);
        btnAsignarFuncion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAsignarFuncionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnAlta, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnAsignarFuncion, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(81, 81, 81)
                .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(61, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAlta, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addComponent(btnAsignarFuncion, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE))
                .addGap(27, 27, 27)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        btnSalir.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel2, 0, 393, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(144, 144, 144)
                        .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnSalir, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-671)/2, (screenSize.height-294)/2, 671, 294);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAltaActionPerformed
        // TODO add your handling code here:
        txtperfil.setEnabled(true);
        txtperfil.requestFocus();
        listaPerfiles.clearSelection();
        btnEliminar.setEnabled(false);
        btnAsignarFuncion.setEnabled(false);
        btnAceptar.setEnabled(true);
        btnCancelar.setEnabled(true);
        btnAlta.setEnabled(false);
    }//GEN-LAST:event_btnAltaActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:

       if(txtperfil.getText().trim().equals("")) {
             JOptionPane.showMessageDialog(this, "Debe ingresar un nombre de Perfil", "Error", JOptionPane.WARNING_MESSAGE);
             txtperfil.requestFocus();
       }
       else {
            guardarPerfil();
       }


    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (listaPerfiles.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar algun perfil para Eliminar", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else {
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                //Obtengo la posicion en la lista del elemento a eliminar
                int pos = listaPerfiles.getSelectedIndex();
                //Le pido al modelo la instancia del perfil a eliminar
                Perfil perfi = (Perfil) modeloPerfiles.get(pos);

                //Verificamos la existencia del perfil en los usuarios
                if (PerfilesDao.getInstance().verificarExistenciaPerfil(conn, perfi.getCod())) {
                    JOptionPane.showMessageDialog(this, "Existen usuarios asignados al perfil que desea eliminar", "Error", JOptionPane.INFORMATION_MESSAGE);
                }
                else {
                    // Consulta si desea eliminar el perfil
                    int rta = JOptionPane.showConfirmDialog(this,
                                        "Esta seguro de eliminar el Perfil?",
                                        "Eliminar",
                                        JOptionPane.YES_NO_OPTION);
                    
                    if(rta == JOptionPane.YES_OPTION){
                    //Si la opcion seleccionada es SI elimina el perfil
                        PerfilesDao.getInstance().eliminar(conn, perfi);
                        modeloPerfiles.remove(pos);
                    }
                }
            }catch(Exception e) {e.printStackTrace();}           
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        actualizarFormulario();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnAsignarFuncionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAsignarFuncionActionPerformed
        AsignacionDeFunciones funciones = new AsignacionDeFunciones(this,true);
        funciones.setPerfil((Perfil)listaPerfiles.getSelectedValue());
        funciones.setVisible(true);
    }//GEN-LAST:event_btnAsignarFuncionActionPerformed

    private void listaPerfilesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaPerfilesMouseClicked
       /*Se habilita cuando se selecciona 1 perfil*/
            btnAsignarFuncion.setEnabled(listaPerfiles.getSelectedValues().length > 0);
            txtperfil.setEnabled(false);
            txtperfil.setText("");
            btnAlta.setEnabled(true);
            btnEliminar.setEnabled(true);
    }//GEN-LAST:event_listaPerfilesMouseClicked

    private void txtperfilKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtperfilKeyPressed
       if(evt.getKeyCode() == 27){
          txtperfil.setEnabled(false);
          txtperfil.setText("");
          btnAlta.setEnabled(true);
          btnEliminar.setEnabled(true);
       }
    }//GEN-LAST:event_txtperfilKeyPressed

    private void listaPerfilesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listaPerfilesKeyPressed
        if(evt.getKeyCode() == 27){
          listaPerfiles.clearSelection();
          btnAsignarFuncion.setEnabled(false);
       }
    }//GEN-LAST:event_listaPerfilesKeyPressed

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAlta;
    private javax.swing.JButton btnAsignarFuncion;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblNombrePerfil;
    private javax.swing.JList listaPerfiles;
    private javax.swing.JTextField txtperfil;
    // End of variables declaration//GEN-END:variables

    private void inicializarFormulario() {
        listaPerfiles.clearSelection();  
    }

    private void actualizarFormulario() {
        txtperfil.setText("");
        txtperfil.setEnabled(false);
        if(!modeloPerfiles.isEmpty()){
            btnEliminar.setEnabled(true);
        }
        btnAceptar.setEnabled(false);
        btnCancelar.setEnabled(false);
        btnAlta.setEnabled(true);
    }

    //Cargamos la lista con los datos de la base
    private void cargarLista() {
        Connection conn = null;
        ArrayList listaPerfiles = null;        
        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            listaPerfiles = PerfilesDao.getInstance().getTodos(conn);
            for (int i=0; i < listaPerfiles.size(); i++) {
                modeloPerfiles.addElement(listaPerfiles.get(i));
            }
        }catch(Exception e) {e.printStackTrace();}
    }

    private void guardarPerfil() {
        Connection conn = null;
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                Perfil perf = new Perfil(txtperfil.getText().toUpperCase().trim());
                PerfilesDao.getInstance().insertar(conn, perf);
                modeloPerfiles.addElement(perf);
                actualizarFormulario();     
            }catch(Exception e) {e.printStackTrace();}
            finally {
                try {
                   JOptionPane.showMessageDialog(this, "El perfil ha sido guardado correctamente!!!", "Guardar", JOptionPane.INFORMATION_MESSAGE);
                }catch(Exception ee) {}
            }

    }

    /**
     * @return the usuarioLogueado
     */
    public Usuario getUsuarioLogueado() {
        return usuarioLogueado;
    }

    /**
     * @param usuarioLogueado the usuarioLogueado to set
     */
    public void setUsuarioLogueado(Usuario usuarioLogueado) {
        this.usuarioLogueado = usuarioLogueado;
    }
}
